import './gulpinit'
import { resolve } from 'path'
import { mkdir, writeFile } from 'fs/promises'
import { copy } from 'fs-extra'
// series 串行（顺序）执行 ，parallel并行执行
import {series, parallel, TaskFunction} from 'gulp'
import { run } from './utils/process'
import { withTaskName } from './utils/gulp'
import { projectRoot, pkgRoot, buildOutput } from "./config/paths"
import {getAllChildName, getChildProjectConfig, mainProjectConfig, packagePath } from "./config"
import type { MainProjectConfigItem } from "./config"
import {PROJECT_NAME} from "./config/constants";

// const MICRO_BUILD_MAIN = process.env.MICRO_BUILD_MAIN || 'all'
// const Main = mainProjectConfig[MICRO_BUILD_MAIN] || null

// 构建主应用与子应用
export const buildMainChild = () => {
  const result: any[] = []
  for(let key in mainProjectConfig){
    const item = mainProjectConfig[key]
    result.push(withTaskName(`buildMain:${key}`, () =>
      run(`pnpm run ${item.buildRun}`)
    ))
  }

  // const childProjectConfig = getChildProjectConfig();
  // for(let key in childProjectConfig){
  //   const item = childProjectConfig[key]
  //   result.push(withTaskName(`buildChild:${key}`, () =>
  //     run(`pnpm run ${item.buildRun}`)
  //   ))
  // }
  const allChildName = getAllChildName();
  allChildName.forEach(child => {
    result.push(withTaskName(`serveChild:${child}`, () =>
      run(`pnpm run -C ${packagePath}/${child} build`)
    ))
  })

  return result
}

const es6SupportedJsData =
  `var supported = true;
// 判断ie
var userAgentForApex = navigator.userAgent;
var agent = userAgentForApex.toLowerCase();
if (agent.indexOf("msie") > -1 || agent.indexOf("trident") > -1) {
  // ie不支持
  console.error('当前浏览器为ie，不允许做业务');
  supported = false;
}
if (supported) {
  // 判断es6
  var arrowFunction ="var t = () => {};";
  try {
    f = new Function(arrowFunction);
    // document.write("当前浏览器支持ES6!");
  } catch (e) {
    // document.write("不支持ES6! "+e);
    console.error('当前浏览器不支持es6', e);
    supported = false;
  }
}
if (!supported) {
  alert("请使用Chrome浏览器访问${PROJECT_NAME}");
  document.getElementById('app').style.display = 'none';
}
`;

const writeEs6SupportedJsFile = async (targetPath: string) => {
  try {
    await writeFile(targetPath, es6SupportedJsData)
    console.log("Es6SupportedJsFile written successfully");
  } catch (err) {
    console.error(err);
  }
}

// 复制生成的子应用到指定生成的主应用中
const copyChildFilesToMain = (mainKey: string, main: MainProjectConfigItem) => {
  const result: TaskFunction[] = []
  // 添加es6SupportedJs文件，先写主工程
  result.push(withTaskName(`writeEs6SupportedJsFileToMain`, async () => {
    await writeEs6SupportedJsFile(resolve(buildOutput, main.rootDir, 'js', 'es6Supported.js'));
  }));
  const allChildName = getAllChildName();
  allChildName.forEach(child => {
    result.push(withTaskName(`copyChild:${child}:to:${mainKey}`, async () => {
        // 添加es6SupportedJs文件，再写子工程
        await writeEs6SupportedJsFile(resolve(pkgRoot, child, 'dist', 'js', 'es6Supported.js'));
        copy(resolve(pkgRoot, child, 'dist'), resolve(buildOutput, main.rootDir, main.buildChildParentName, child), {recursive: true})
      }
    ))
  })

  if (result.length > 0) {
    return parallel(...result)
  } else {
    return null;
  }
}

// 复制指定生成完的主应用与旗下子应用
export const copyBuildMainChild = (mainKey: string, main: MainProjectConfigItem) => {
  const seriesResult: any[] = [];

  // 复制主框架
  seriesResult.push(withTaskName(`copyMain:${mainKey}`, () =>
    copy(resolve(projectRoot, main.rootDir, main.outputDir), resolve(buildOutput, main.rootDir), { recursive: true })
  ))

  // 复制生成的子应用到指定主应用
  const childSeries = copyChildFilesToMain(mainKey, main);

  if (childSeries != null) {
    // 在复制的主框架内部创建子应用上级目录
    seriesResult.push(withTaskName(`${mainKey}:createChildOutput`, () =>
      mkdir(resolve(buildOutput, main.rootDir, main.buildChildParentName), { recursive: true })
    ))

    seriesResult.push(childSeries)
  }

  return series(...seriesResult)

}

// 复制所有生成完的主应用与子应用入口
export const copyMainChildFiles = () => {
  const result: any[] = []
  for(let key in mainProjectConfig){
    const item = mainProjectConfig[key]
    result.push(copyBuildMainChild(key, item))
  }
  return result
}

export default series(
  withTaskName('clean', () => run('pnpm run clean')),
  withTaskName('createOutput', () => mkdir(buildOutput, { recursive: true })),
  parallel(...buildMainChild()),
  parallel(...copyMainChildFiles())
)
